<template>
  <div class="register-page">
    <div class="background"></div>
    <div class="form-container">
      <h2>用户注册</h2>
      <form @submit.prevent="handleRegister">
        <div class="input-group">
          <input v-model="form.name" placeholder="真实姓名">
        </div>
        <div class="input-group">
          <input 
            v-model="form.phone"
            placeholder="手机号"
            @input="validatePhone"
          >
          <span v-if="phoneError" class="error">{{ phoneError }}</span>
        </div>
        <div class="input-group">
          <input
            v-model="form.password"
            type="password"
            placeholder="密码（8位）"
            maxlength="8"
          >
        </div>
        <button type="submit">注册学生账号</button>
        <p class="login-link" @click="goLogin">已有账号？立即登录</p>
      </form>
    </div>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue';
import { useRouter } from 'vue-router';
import { registerUser } from '@/api/user';
import { ElMessage } from 'element-plus';

const router = useRouter();

const form = reactive({
  name: '',
  phone: '',
  password: '',
  role: 'student' 
});

const phoneError = ref('');

const validatePhone = () => {
  const phoneRegex = /^1[3-9]\d{9}$/;
  phoneError.value = phoneRegex.test(form.phone) ? '' : '无效手机号';
};

const handleRegister = async () => {
  try {
    if (!form.name || !form.phone || !form.password) {
      throw new Error('请填写完整信息');
    }
    const phoneRegex = /^1[3-9]\d{9}$/;
    if (!phoneRegex.test(form.phone)) {
      throw new Error('手机号格式错误');
    }
    if (form.phone === '19999999999' || form.phone === '18888888888') {
      throw new Error('该手机号为系统保留号码');
    }
    await registerUser(form);
    ElMessage.success('注册成功！');
    router.push('/login');
  } catch (error) {
    phoneError.value = error.message;
    setTimeout(() => phoneError.value = '', 3000);
  }
};

const goLogin = () => router.push('/login');
</script>

<style scoped>
.register-page {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  position: relative;
}

.background {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: url('@/assets/bg.png') no-repeat center/cover;
  filter: blur(3px);
  z-index: -1;
}

.form-container {
  background: rgba(255, 255, 255, 0.9);
  padding: 2rem;
  border-radius: 10px;
  width: 400px;
}

.role-select button {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  margin: 0 1rem;
  border: 2px solid #ccc;
  cursor: pointer;
}

.role-select button.active {
  border-color: #409eff;
  background: #ecf5ff;
}

.input-group {
  margin: 1rem 0;
}

input {
  width: 100%;
  padding: 0.8rem;
  border: 1px solid #ddd;
  border-radius: 4px;
}
</style>